//
//  InsureDetailListController.m
//  华康通
//
//  Created by leiyu on 16/11/9.
//  Copyright © 2016年 com.huakang. All rights reserved.
//

#import "InsureDetailListController.h"
#import "InsureDetailListCell.h"
#import "InsureDetailListFirstCell.h"
#import "JSONFromOrderDetail.h"
#import "UMMobClick/MobClick.h"
#import "PayBDViewController.h"
#import "InsureDetailListMode.h"

@interface InsureDetailListController ()<UIScrollViewDelegate, UIWebViewDelegate,NSURLSessionDownloadDelegate>

@property (strong, nonatomic) IBOutlet UIButton *bottomButton;
@property (strong, nonatomic) IBOutlet UILabel *titleLabel;
@property (strong, nonatomic) IBOutlet UIImageView *productLogoImageView;
@property (nonatomic, strong) NSArray* sections;
@property (weak, nonatomic) IBOutlet UIView *bottomView;


//h5页面传过来的值，
@property (nonatomic, strong) NSString* h5Str;

//电子保单webview
@property (nonatomic, strong) UIWebView* webView;
//电子保单背景透明视图
@property (nonatomic, strong) UIView* backView;
//关闭按钮
@property (nonatomic, strong) UIButton* closeButton;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;

@property (nonatomic, strong) NSURLSession *session;

@property (nonatomic, strong) InsureDetailListMode* mode;

//悬浮一个按钮是查看电子保单的
@property (nonatomic, strong) UIButton* suspensionButton;

@end

@implementation InsureDetailListController

//懒加载
- (NSURLSession *)session
{
    if (!_session)
    {
        // 获得session
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

- (UIButton*)suspensionButton
{
    if (!_suspensionButton)
    {
        _suspensionButton = [[UIButton alloc]init];
        _suspensionButton.frame = CGRectMake(UISCREENWEITH - 140, UISCREENHEIGHT - 60, 120, 40);
        _suspensionButton.layer.cornerRadius = 20.0;
        //添加按钮阴影
        _suspensionButton.layer.shadowOffset = CGSizeMake(1, 1);
        _suspensionButton.layer.shadowOpacity = 0.4;
        _suspensionButton.layer.shadowColor = YYColor.CGColor;
        [_suspensionButton setTitle:@"查看电子保单" forState:UIControlStateNormal];
        _suspensionButton.titleLabel.font = SetFont(14.0);
        [_suspensionButton setTitleColor:FFFFFFColor forState:UIControlStateNormal];
        _suspensionButton.backgroundColor = KMainColor;
        [_suspensionButton addTarget:self action:@selector(showDZBD) forControlEvents:UIControlEventTouchUpInside];
    }
    return _suspensionButton;
}

- (UIButton*)closeButton
{
    if (!_closeButton)
    {
//        _closeButton = [[UIButton alloc]init];
//        _closeButton.frame = CGRectMake((UISCREENWEITH - 30)/2, UISCREENHEIGHT - 44 + 7, 30, 30);
//        [_closeButton setImage:LoadImage(@"close.png") forState:UIControlStateNormal];
//        _closeButton.backgroundColor = ClEARColor;
//        [_closeButton addTarget:self action:@selector(closeWebView) forControlEvents:UIControlEventTouchUpInside];
        _closeButton = [[UIButton alloc]init];
        _closeButton.frame = CGRectMake(0, UISCREENHEIGHT - 50, UISCREENWEITH, 50);
        [_closeButton setTitle:@"点击关闭" forState:UIControlStateNormal];
        _closeButton.titleLabel.font = SetFont(20.0);
        [_closeButton setTitleColor:FFFFFFColor forState:UIControlStateNormal];
        _closeButton.backgroundColor = KMainColor;
        [_closeButton addTarget:self action:@selector(closeWebView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeButton;
}

- (UIView*)backView
{
    if (!_backView)
    {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, UISCREENWEITH, UISCREENHEIGHT - 20)];
        _backView.backgroundColor = YYColor;
        _backView.alpha = 0.75;
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(deleteBackView:)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        [_backView addGestureRecognizer:tap];
    }
    return _backView;
}

- (UIWebView*)webView
{
    if (!_webView)
    {
        _webView = [[UIWebView alloc]initWithFrame: CGRectMake(0, 20, UISCREENWEITH, UISCREENHEIGHT - 70)];
        _webView.backgroundColor = FFFFFFColor;
        //支持手势捏合放大缩小
        _webView.scalesPageToFit = YES;
//        _webView.layer.cornerRadius = 5.0;
//        _webView.layer.masksToBounds = YES;
        _webView.delegate = self;
    }
    return _webView;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

//拿到h5页面的链接
- (NSString*)returnURL
{
    if (![self.payUrl isEqualToString:@""] && [self.receiptUrl isEqualToString:@""])
    {
        return self.payUrl;
    }
    if (![self.receiptUrl isEqualToString:@""] && [self.payUrl isEqualToString:@""])
    {
        return self.receiptUrl;
    }
    else
    {
        return @"";
    }
}



//为了方便某些时候能够在页面呈现的时候刷新数据，另外写一个方法
- (void)newLoad
{
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.h5Str = @"0";
    self.title = @"投保单详情";
    self.titleLabel.text = self.productName;
    NSLog(@"支付链接self.orderStatus = %@ \n提交回执链接:self.receiptUrl = %@",self.payUrl,self.receiptUrl);
    if (![self.payFlag isEqualToString:@""] && ![self.payFlag isEqualToString:@"查看详情"])
    {
        [self.bottomButton setHidden:NO];
        [self.bottomButton setTitle:self.payFlag forState:UIControlStateNormal];
        self.bottomView.frame = CGRectMake(0, 0, UISCREENWEITH, 80);
    }
    else
    {
        [self.bottomButton setHidden:YES];
        self.bottomView.frame = CGRectZero;
    }
//    if (![self.payUrl isEqualToString:@""] && ![self.receiptUrl isEqualToString:@""])
//    {
//        [self.bottomButton setHidden:NO];
//        self.bottomView.frame = CGRectMake(0, 0, UISCREENWEITH, 150);
//    }
//    else if ([self.payUrl isEqualToString:@""] && ![self.receiptUrl isEqualToString:@""])
//    {
//        [self.bottomButton setHidden:YES];
//        self.bottomView.frame = CGRectMake(0, 0, UISCREENWEITH, 48+16+16);
//    }
//    else if (![self.payUrl isEqualToString:@""] && [self.receiptUrl isEqualToString:@""])
//    {
//        [self.bottomButton setHidden:NO];
//        self.bottomView.frame = CGRectMake(0, 0, UISCREENWEITH, 48+16+16);
//    }
//    else if ([self.payUrl isEqualToString:@""] && [self.receiptUrl isEqualToString:@""])
//    {
//        [self.bottomButton setHidden:YES];
//        self.bottomView.frame = CGRectZero;
//    }
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
    
    self.bottomButton.layer.cornerRadius = 3.0;
    self.bottomButton.layer.masksToBounds = YES;
    [self.tableView registerNib:[UINib nibWithNibName:@"InsureDetailListCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"InsureDetailListFirstCell" bundle:nil] forCellReuseIdentifier:@"oneCell"];
    [self postHKInsOrderDetail];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"InsureDetailListController"];//("PageOne"为页面名称，可自定义)
    //如果确定有显示的点子保单，显示“查看电子保单”按钮
    if ([self.isDownPolicy isEqualToString:@"1"])
    {
         [[UIApplication sharedApplication].keyWindow addSubview:self.suspensionButton];
    }
    if ([self.h5Str isEqualToString:@"1"])
    {
        [self.bottomButton setHidden:YES];
        //列表回到最顶端
        [self.tableView setContentOffset:CGPointMake(0,0) animated:YES];
        //把底部试图去掉
        self.bottomView.frame = CGRectZero;
        //刷新表格
        [self postHKInsOrderDetail];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [MobClick endLogPageView:@"InsureDetailListController"];
    [self.suspensionButton removeFromSuperview];
    self.suspensionButton = nil;
}

- (void)deleteBackView:(UITapGestureRecognizer*)gr
{
    [self closeWebView];
}

- (void)closeWebView
{
    [self.webView removeFromSuperview];
    self.webView = nil;
    [self.backView removeFromSuperview];
    self.backView = nil;
    [self.closeButton removeFromSuperview];
    self.closeButton = nil;
}

#pragma  mark - webView代理方法

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    //[SVProgressHUD showWithStatus:@"加载中..." maskType:SVProgressHUDMaskTypeNone];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //[SVProgressHUD dismiss];
}


#pragma  mark - 下载电子保单(直接查看)


//弹出提示功能 无法获取该保单的订单号
- (void)showNoGetOrderNoWithMessage:(NSString*)message
{
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    TextStatusView *customView  = [TextStatusView view];
    customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
    customView.bottomLabel.text = message;
    //    customView.layer.cornerRadius = 7.0;
    //    customView.layer.masksToBounds = YES;
    [alertView setContainerView:customView];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确定", nil]];
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex)
        {
            case 0:
                return ;
                break;
            default:
                return;
                break;
        }
    }];
    [alertView show];
}

- (void)showDZBD
{
    NSDictionary* json;
    if (self.orderNo)
    {
        json = @{@"platformType":@"1",
                 @"orderType":@"01",
                 @"requestService":@"paDownloadPolicyNew",
                 @"requestObject":@{@"orderNo":[NSString stringWithFormat:@"%@",self.orderNo],
                                    @"url":@""
                                    }
                 };
 /*
        json = @{@"platformType":@"1",
                 @"orderType":@"01",
                 @"requestService":@"paDownloadPolicyNew",
                 @"requestObject":@{@"orderNo":[NSString stringWithFormat:@"%@",@"20170907010006849"],
                                    @"url":@""
                                    }
                 };
*/
        //字符串转字符串
        NSString* str = [JSONToString dictionaryToJson:json];
        //转md5
        MyAdditions* md5 = [[MyAdditions alloc]init];
        md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
        NSString* md5_Str = [md5 md5];
        NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
        [self getPaDownloadPolicyNewWithURL:url withParam:json];
    }
    else
    {
        [self showNoGetOrderNoWithMessage:@"无法获取该保单的订单号！"];
    }
}

- (void)getPaDownloadPolicyNewWithURL:(NSString*)url withParam:(NSDictionary*)json
{
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstanceWithTitle:@"检测到您的设备没有连接网络!" withImageStr:@"no_record" withType:0 withFrame:self.view.frame withVC:self];
    [networking showNetworkViewWithSuccess:^{
        
        [XHNetworking POST:url parameters:json success:^(NSData *responseObject) {
            [self readPaDownloadPolicyNewWithData:responseObject];
        } failure:^(NSError *error) {
            NSLog(@"error.code = %@",error.userInfo);
            dispatch_async(dispatch_get_main_queue(), ^{
                XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                [statusBar showStatusMessage:@"下载失败"];
            });
        }];
    } failure:^{
        nil;
    } click:^(NSInteger type) {
        NSLog(@"点击了什么类型的按钮%ld!",(long)type);
        if (type == 0)
        {
            
        }
    }];
}

//显示电子保单
- (void)showDZBDForSelfWithFile:(NSURL*)url
{
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    [[UIApplication sharedApplication].keyWindow addSubview:self.backView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.webView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.closeButton];
}

//开始下载保单
- (void)startWithURl:(NSString*)urlString
{
    //获取本地是否已经下载了电子保单
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *filePath = [paths lastObject];
    NSString* newFile = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf",self.orderNo]];
    if ([[NSFileManager defaultManager]fileExistsAtPath:newFile])
    {
        //已经下载
        NSLog(@"本地已经下载有了电子保单,保单地址:%@",newFile);
        [self showDZBDForSelfWithFile:[NSURL fileURLWithPath:newFile]];
    }
    else
    {
        [SVProgressHUD showInfoWithStatus:@""];
        NSURL* url = [NSURL URLWithString:urlString];
        NSURLRequest* request = [NSURLRequest requestWithURL:url];
        self.task = [self.session downloadTaskWithRequest:request];
        [self.task resume];
    }
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *filePath = [paths lastObject];
    NSString* newFile = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf",self.orderNo]];
    NSURL* newURL = [NSURL fileURLWithPath:newFile];
    NSLog(@"newURL = %@ newFile = %@",newURL,newFile);
    if ([[NSFileManager defaultManager]copyItemAtURL:location toURL:newURL error:nil])
    {
        NSLog(@"下载成功");
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
        dispatch_after(delay, dispatch_get_main_queue(), ^{
            [self showDZBDForSelfWithFile:newURL];
        });
    }
    else
    {
        NSLog(@"下载失败");
        XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
        [statusBar showStatusMessage:@"下载失败"];
    }
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //更新下载进度
    [self totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
}

/**
 *  恢复下载后调用，
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
    NSLog(@"恢复下载后调用");
}

//根据下载进度更新视图
-(void)totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    CGFloat progressF = totalBytesWritten/1024.0/1024.0;
    CGFloat allF = totalBytesExpectedToWrite/1024.0/1024.0;
//    NSString* str = [NSString stringWithFormat:@"已下载%.0lf%%",progressF/allF * 100];
//    [SVProgressHUD showWithStatus:str maskType:SVProgressHUDMaskTypeNone];
    [SVProgressHUD showInfoWithStatus:@""];
    if (progressF/allF == 1.0)
    {
//        [SVProgressHUD showSuccessWithStatus:@"完成下载" maskType:SVProgressHUDMaskTypeNone];
        XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
        [statusBar showStatusMessage:@"完成下载"];
    }
}

//iOS 去掉html标签 留下原本的字符串
-(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    return html;
}

//展示电子保单
- (void)readPaDownloadPolicyNewWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"下载电子保单(直接查看)json = %@",json);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"])
            {
                if ([json[@"responseObject"] isKindOfClass:[NSDictionary class]] && json[@"responseObject"])
                {
                    if (json[@"responseObject"][@"url"] && ![json[@"responseObject"][@"url"] isEqualToString:@""])
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //直接打开电子保单
                            //转码
                            NSString* encodedString = [json[@"responseObject"][@"url"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                            NSLog(@"电子保单下载地址：%@",encodedString);
                            //下载打开电子保单
                            [self startWithURl:encodedString];
                        });
                    }
                    else
                    {
                        if (![json[@"responseObject"][@"message"] isEqualToString:@""] && json[@"responseObject"][@"message"])
                        {
                            NSString *htmlStr = json[@"responseObject"][@"message"];
                            NSString *message = [self filterHTML:htmlStr];
                            NSLog(@"message = %@",message);
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [self showNoGetOrderNoWithMessage:htmlStr];
                                [SVProgressHUD dismiss];
                            });
                        }
                        else
                        {
                            [self showError];
                        }
                    }
                }
                else
                {
                    [self showError];
                }
            }
            else
            {
                [self showError];

            }
        }
        else
        {
            [self showError];

        }
    });
}

- (void)showError
{
    dispatch_async(dispatch_get_main_queue(), ^{
        XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
        [statusBar showStatusMessage:@"下载失败"];
    });
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //CGPoint point = scrollView.contentOffset;
    //self.suspensionButton.frame = CGRectMake(UISCREENWEITH - 100, UISCREENHEIGHT - 64 - 40 - 20 + point.y, 80, 40);
}

#pragma mark  //获取订单列表

- (void)postHKInsOrderDetail
{
    //设置缓存的key
    NSString* cacheStr;
    cacheStr = [NSString stringWithFormat:@"getHKInsOrderDetail_%ld_%@",(long)self.myType,self.orderNo];
    NSDictionary* json;
    // [TRUserAgenCode getCustomerId];
    if (self.myType == InsureDetailListControllerTypeShort)
    {
        json = @{@"platformType":@"1",
                 @"orderType":@"01",
                 @"requestService":@"getHKTravelOrderDetail",
                 @"requestObject":@{@"orderNo":self.orderNo}
                 };
    }
    else if (self.myType == InsureDetailListControllerTypeLong)
    {
        json = @{@"platformType":@"1",
                 @"orderType":@"01",
                 @"requestService":@"getHKInsOrderDetail",
                 @"requestObject":@{@"orderNo":self.orderNo}
                 };
    }
    NSLog(@"json = %@",json);
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    NSLog(@"url = %@",url);
    [self getHKInsOrderDetailWithURL:url withParam:json withCacheStr:cacheStr];
}

//读取网络或本地的订单详情数据
- (void)readHKInsOrderDetailWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"获取订单详情json = %@",json);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"] && [json[@"responseObject"] isKindOfClass:[NSDictionary class]])
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSMutableArray* arr = [NSMutableArray array];
                    JSONFromOrderDetail* product = [JSONFromOrderDetail HkOrderListWithJSON:json[@"responseObject"]];
                    self.picUrl = product.statusPic;
                    [self.productLogoImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE_URL,product.brandLogo]]];
                    if ([product.brandLogo rangeOfString:HTTP].location != NSNotFound)
                    {
                        [self.productLogoImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",product.brandLogo]]];
                    }
                    [arr addObject:@{@"title":@"保单信息",@"detail":@[
                                             @{@"保单号":product.insuranceOrderNo,@"投保单号":product.orderId,@"订单号":product.orderNo,@"image":product.statusPic,@"保障期间":[NSString stringWithFormat:@"%@至%@",product.startDate,product.endDate]}
                                             ]}];
                    [self getFJXWithList:product withMutableArray:arr];
                    [arr addObject:@{@"title":@"投保人信息",@"detail":@[
                                             [NSString stringWithFormat:@"姓名：%@",product.name],
                                             [NSString stringWithFormat:@"证件类型：%@",product.idTypeName],
                                             [NSString stringWithFormat:@"证件号：%@",product.idNo],
                                             [NSString stringWithFormat:@"手机号：%@",product.mobile],
                                             [NSString stringWithFormat:@"邮箱：%@",product.email]
                                             ]}];
                    [self getBBRWithList:product withMutableArray:arr];
                    [arr addObject:@{@"title":@"受益人信息",@"detail":@[[NSString stringWithFormat:@"受益人：%@",product.bnfString]]}];
                    [self getSYRWithList:product withMutableArray:arr];
                    if (self.myType == InsureDetailListControllerTypeLong)
                    {
                        //如果不是恒大产品
                        if ([self.productName rangeOfString:@"恒大"].location == NSNotFound)
                        {
                            if (product.orderHKDetailAmountDTO.allKeys.count == 0)
                            {
                                [arr addObject:@{@"title":@"首年保费结算信息",@"detail":@[
                                                         [NSString stringWithFormat:@"保额：%@元",product.amt],
                                                         [NSString stringWithFormat:@"保费：%@元",product.amount],
                                                         [NSString stringWithFormat:@"交费年限：%@",product.payYears],
                                                         [NSString stringWithFormat:@"交费方式：%@",product.payIntvName]
                                                         ]}];
                            }
                            else
                            {
                                //                            [arr addObject:@{@"title":@"首年保费结算信息",@"detail":@[
                                //                                                     [NSString stringWithFormat:@"保额：%@元",product.orderHKDetailAmountDTO[@"amt"]],
                                //                                                     [NSString stringWithFormat:@"保费：%@元",product.orderHKDetailAmountDTO[@"amount"]],
                                //                                                     [NSString stringWithFormat:@"交费年限：%@",product.orderHKDetailAmountDTO[@"payYears"]],
                                //                                                     [NSString stringWithFormat:@"交费方式：%@",product.orderHKDetailAmountDTO[@"payIntvName"]]
                                //                                                     ]}];
                                [arr addObject:@{@"title":@"首年保费结算信息",@"detail":@[
                                                         [NSString stringWithFormat:@"保费：%@元",product.orderHKDetailAmountDTO[@"amount"]]
                                                         ]}];
                            }
                        }
                        [arr addObject:@{@"title":@"首年保费支付信息",@"detail":@[
                                                 [NSString stringWithFormat:@"续期交费银行：%@",product.bankName],
                                                 [NSString stringWithFormat:@"续期交费户名：%@",product.cardHolder],
                                                 [NSString stringWithFormat:@"续期缴费账号：%@",product.cardBookCode]
                                                 ]}];
                    }
                    else
                    {
                        [arr addObject:@{@"title":@"首年保费结算信息",@"detail":@[
                                                 [NSString stringWithFormat:@"保费 ：%@元",product.amount]
                                                 ]}];
                    }
                    self->_sections = [arr copy];
                    [self.tableView reloadData];
                });
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                });
            }
        }
        
    });
    
}
//得到附加险种数组
- (void)getFJXWithList:(JSONFromOrderDetail*)list withMutableArray:(NSMutableArray*)array
{
    NSMutableArray* a1 = [NSMutableArray array];
    NSMutableArray* a2 = [NSMutableArray array];
    for (NSDictionary* dic in list.riskList)
    {
        if ([dic[@"isMainRisk"] integerValue] != 1)
        {
            [a1 addObject:dic];
        }
        else
        {
            [a2 addObject:dic];
        }
    }
    if (a2.count > 0)
    {
        for (int i = 0;i < a2.count;i++)
        {
            NSDictionary* dic = a2[i];
            [array addObject:@{@"title":[NSString stringWithFormat:@"险种信息"],@"detail":@[
                                       [NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",dic[@"riskName"]]],
                                       [NSString stringWithFormat:@"缴费方式：%@",[NSString stringWithFormat:@"%@",dic[@"payIntv"]]],
                                       [NSString stringWithFormat:@"保险期间：%@",[NSString stringWithFormat:@"%@",dic[@"years"]]],
                                       [NSString stringWithFormat:@"保额：%@元",[NSString stringWithFormat:@"%@",dic[@"amt"]]],
                                       [NSString stringWithFormat:@"交费期间：%@",[NSString stringWithFormat:@"%@",dic[@"payYears"]]],
                                       [NSString stringWithFormat:@"份数：%@份",[NSString stringWithFormat:@"%@",dic[@"mult"]]],
                                       [NSString stringWithFormat:@"保费：%@元",[NSString stringWithFormat:@"%@",dic[@"prem"]]],
                                       ]}];
        }
    }
    if (a1.count > 0)
    {
        for (int i = 0;i < a1.count;i++)
        {
            NSDictionary* dic = a1[i];
            [array addObject:@{@"title":[NSString stringWithFormat:@"附加险%@",[self arabicNumeralsToChinese:i]],@"detail":@[
                                       [NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",dic[@"riskName"]]],
                                       [NSString stringWithFormat:@"缴费方式：%@",[NSString stringWithFormat:@"%@",dic[@"payIntv"]]],
                                       [NSString stringWithFormat:@"保险期间：%@",[NSString stringWithFormat:@"%@",dic[@"years"]]],
                                       [NSString stringWithFormat:@"保额：%@元",[NSString stringWithFormat:@"%@",dic[@"amt"]]],
                                       [NSString stringWithFormat:@"交费期间：%@",[NSString stringWithFormat:@"%@",dic[@"payYears"]]],
                                       [NSString stringWithFormat:@"份数：%@份",[NSString stringWithFormat:@"%@",dic[@"mult"]]],
                                       [NSString stringWithFormat:@"保费：%@元",[NSString stringWithFormat:@"%@",dic[@"prem"]]],
                                       ]}];
        }
    }
}

//阿拉伯数字转成汉字
- (NSString *)arabicNumeralsToChinese:(NSInteger)number
{
    switch (number) {
        case 0:
            return @"一";
            break;
        case 1:
            return @"二";
            break;
        case 2:
            return @"三";
            break;
        case 3:
            return @"四";
            break;
        case 4:
            return @"五";
            break;
        case 5:
            return @"六";
            break;
        case 6:
            return @"七";
            break;
        case 7:
            return @"八";
            break;
        case 8:
            return @"九";
            break;
        case 9:
            return @"十";
            break;
        case 10:
            return @"十一";
            break;
        case 11:
            return @"十二";
            break;
        case 12:
            return @"十三";
            break;
        case 13:
            return @"十四";
            break;
        case 14:
            return @"十五";
            break;
        case 15:
            return @"十六";
            break;
        case 16:
            return @"十七";
            break;
        case 17:
            return @"十八";
            break;
        case 18:
            return @"十九";
            break;
        case 19:
            return @"二十";
            break;
        case 20:
            return @"二十一";
            break;
        default:
            return @"";
            break;
    }
}

//得到受益人信息数组
- (void)getSYRWithList:(JSONFromOrderDetail*)list withMutableArray:(NSMutableArray*)array
{
    for (int i = 0;i < list.bnfList.count;i++)
    {
        NSDictionary* dic = list.bnfList[i];
        [array addObject:@{@"title":[NSString stringWithFormat:@"第%@受益人",[self getChineseCharactersWithIndex:i]],@"detail":@[
                                   [NSString stringWithFormat:@"与被保人关系：%@",dic[@"relationToInsured"]],
                                   [NSString stringWithFormat:@"姓名：%@",dic[@"name"]],
                                   [NSString stringWithFormat:@"证件类型：%@",dic[@"idTypeName"]],
                                   [NSString stringWithFormat:@"证件号：%@",dic[@"idNo"]],
                                   [NSString stringWithFormat:@"收益比例（％）：%@",dic[@"bnfLot"]]]}];
    }
}

//第几受益人转成汉字
- (NSString*)getChineseCharactersWithIndex:(NSInteger)index
{
    switch (index) {
        case 0:
            return @"一";
            break;
        case 1:
            return @"二";
            break;
        case 2:
            return @"三";
            break;
        case 3:
            return @"四";
            break;
        case 4:
            return @"五";
            break;
        case 5:
            return @"六";
            break;
        case 6:
            return @"七";
            break;
        case 7:
            return @"八";
            break;
        case 8:
            return @"九";
            break;
        case 9:
            return @"十";
            break;
        case 10:
            return @"十一";
            break;
        case 11:
            return @"十二";
            break;
        case 12:
            return @"十三";
            break;
        case 13:
            return @"十四";
            break;
        case 14:
            return @"十五";
            break;
        case 15:
            return @"十六";
            break;
        case 16:
            return @"十七";
            break;
        case 17:
            return @"十八";
            break;
        case 18:
            return @"十九";
            break;
        case 19:
            return @"二十";
            break;
        case 20:
            return @"二十一";
            break;
        default:
            return @"";
            break;
    }
}

//得到被保人(被保车辆)信息数组
- (void)getBBRWithList:(JSONFromOrderDetail*)list withMutableArray:(NSMutableArray*)array
{
    id carDTO = list.orderCarDTO;
    NSArray* arr = (NSArray*)carDTO;
    if (![carDTO isKindOfClass:[NSArray class]] || arr.count == 0)
    {
        //如果没有车险的车辆信息，既非车辆投保
        if (list.insuredList.count == 0)
        {
            [array addObject:@{@"title":[NSString stringWithFormat:@"被保人信息"],@"detail":@[
                                       [NSString stringWithFormat:@"与投保人关系：%@",@"本人"],
                                       [NSString stringWithFormat:@"购买份数（份）：%@",@"1"]]}];
        }
        else
        {
            for (int i = 0;i < list.insuredList.count;i++)
            {
                NSDictionary* dic = list.insuredList[i];
                if ([dic[@"relationToAppnt"] isEqualToString:@"本人"])
                {
                    [array addObject:@{@"title":[NSString stringWithFormat:@"被保人信息"],@"detail":@[
                                               [NSString stringWithFormat:@"与投保人关系：%@",dic[@"relationToAppnt"]],
                                               [NSString stringWithFormat:@"购买份数（份）：%@",list.mult]]}];
                }
                else
                {
                    [array addObject:@{@"title":[NSString stringWithFormat:@"被保人信息"],@"detail":@[
                                               [NSString stringWithFormat:@"与投保人关系：%@",dic[@"relationToAppnt"]],
                                               [NSString stringWithFormat:@"姓名：%@",dic[@"name"]],
                                               [NSString stringWithFormat:@"证件类型：%@",dic[@"idTypeName"]],
                                               [NSString stringWithFormat:@"证件号：%@",dic[@"idNo"]],
                                               [NSString stringWithFormat:@"手机号码：%@",dic[@"mobile"]],
                                               [NSString stringWithFormat:@"购买份数（份）：%@",list.mult]]}];
                }
            }
        }
    }
    else
    {
        //如果有车险的车辆信息
        for (int i = 0;i < arr.count;i++)
        {
            NSDictionary* dic = list.orderCarDTO[i];
            [array addObject:@{@"title":[NSString stringWithFormat:@"车辆信息"],@"detail":@[
                                       [NSString stringWithFormat:@"车辆类型：%@",@"乘用车辆"],
                                       [NSString stringWithFormat:@"使用性质：%@",@"非营业"],
                                       [NSString stringWithFormat:@"车辆号码：%@",dic[@"licenseNo"]],
                                       [NSString stringWithFormat:@"厂牌型号：%@",dic[@"brandName"]],
                                       [NSString stringWithFormat:@"车驾驶号：%@",dic[@"frameNo"]],
                                       [NSString stringWithFormat:@"核定座位：%@",dic[@"carSeatCount"]],
                                       [NSString stringWithFormat:@"投保座位：%@",dic[@"carSeatCountAppnt"]]]}];
        }
    }
}

- (void)getHKInsOrderDetailWithURL:(NSString*)url withParam:(NSDictionary*)param withCacheStr:(NSString*)cacheStr
{
    NSLog(@"cacheStr = %@",cacheStr);
    
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstanceWithTitle:@"检测到您的设备没有连接网络!" withImageStr:@"no_record" withType:0 withFrame:self.view.frame withVC:self];
    [networking showNetworkViewWithSuccess:^{
        
        [XHNetworking POST:url parameters:param cacheStr:cacheStr jsonCache:^(id jsonCache) {
            //无网络得到缓存 从缓存读取缓存信息;
            [self readHKInsOrderDetailWithData:jsonCache];
        } success:^(NSData *responseObject) {
            //网络读取数据
            [self readHKInsOrderDetailWithData:responseObject];
        } failure:^(NSError *error) {
            //        [self endRefresh];
            NSLog(@"error.code = %@",error.userInfo);
        }];
        
    } failure:^{
        nil;
    } click:^(NSInteger type) {
        NSLog(@"点击了什么类型的按钮%ld!",(long)type);
        if (type == 0)
        {
            
        }
    }];
}

- (void)popRootVC
{
    if (self.returnValueBlock)
    {
        self.returnValueBlock(self.h5Str);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

//立即支付   //查看提交回执页面
- (IBAction)pay:(UIButton *)sender
{
    NSLog(@"立即支付恒大产品.............");
    PayBDViewController* bdVC = [[PayBDViewController alloc]initWithNibName:@"PayBDViewController" bundle:nil];
    bdVC.index = 0;
    if (![self.receiptUrl isEqualToString:@""])
    {
        bdVC.index = 1;
    }
//    if (bdVC.index == 0)
//    {
    //拿到H5页面的判断是否刷新页面的值；
    bdVC.returnValueBlock = ^(NSString *strValue) {
        self.h5Str = strValue;
    };
//    }
    bdVC.url = [self returnURL];
    bdVC.orderNo = self.orderNo;
    
    [self.navigationController pushViewController:bdVC animated:YES];
}

//得到设置label 不同的颜色
- (NSMutableAttributedString*)getLabelAllColor:(NSString*)str
{
    NSMutableAttributedString *stra = [[NSMutableAttributedString alloc] initWithString:str];
    if ([str rangeOfString:@"："].location != NSNotFound)
    {
        NSArray* arr = [str componentsSeparatedByString:@"："];
        [stra addAttribute:NSForegroundColorAttributeName value:SHOWCOLOR(@"3E3E3E") range:NSMakeRange([arr[0] length] + 1,str.length - [arr[0] length] - 1 )];
        [stra addAttribute:NSForegroundColorAttributeName value:SHOWCOLOR(@"A7A7A7") range:NSMakeRange(0,[arr[0] length] + 1)];
        if ([str rangeOfString:@"保单状态"].location != NSNotFound)
        {
            [stra addAttribute:NSForegroundColorAttributeName value:KMainColor range:NSMakeRange([arr[0] length] + 1,str.length - [arr[0] length] - 1 )];
        }
    }
    else
    {
        [stra addAttribute:NSForegroundColorAttributeName value:SHOWCOLOR(@"A7A7A7") range:NSMakeRange(0,str.length)];
    }
    return stra;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.sections[section][@"detail"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        InsureDetailListFirstCell* cell = [tableView dequeueReusableCellWithIdentifier:@"oneCell"];
        if (cell == nil)
        {
            //直接加载 xib
            cell = [[[NSBundle mainBundle]loadNibNamed:@"InsureDetailListFirstCell" owner:self options:nil] lastObject];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        InsureDetailListMode* mode = [InsureDetailListMode mode];
        mode.ddStr = [NSString stringWithFormat:@"订单号：%@",self.sections[indexPath.section][@"detail"][0][@"订单号"]];
        mode.tbStr = [NSString stringWithFormat:@"投保单号：%@",self.sections[indexPath.section][@"detail"][0][@"投保单号"]];
        mode.bdStr = [NSString stringWithFormat:@"保单号：%@",self.sections[indexPath.section][@"detail"][0][@"保单号"]];
        mode.bdStuesStr = [NSString stringWithFormat:@"保单状态：%@",self.picUrl];
        if (self.myType == InsureDetailListControllerTypeLong)
        {
            mode.bzStr = @"保障期间：以保险公司出具的保单为准";
        }
        else
        {
            mode.bzStr = [NSString stringWithFormat:@"保障期间：%@",self.sections[indexPath.section][@"detail"][0][@"保障期间"]];
        }
        [cell setModel:mode];
        [cell setNeedsDisplay];
        return cell;
    }
    else
    {
        InsureDetailListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.leftLabel.attributedText = [self getLabelAllColor:[NSString stringWithFormat:@"%@",self.sections[indexPath.section][@"detail"][indexPath.row]]];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        return cell.bounds.size.height;
    }
    else
    return 27.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 26.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 26)];
    view.backgroundColor = LIGHTGREYColor;
    view.layer.borderColor = F0F0F0Color.CGColor;
    view.layer.borderWidth = 1.0;
    UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(16, 0, view.frame.size.width, 26)];
    label.textColor = [UIColor colorWithRed:152.0/255.0 green:152.0/255.0 blue:152.0/255.0 alpha:1.0];
    label.font = SetFont(14.0);
    label.text = self.sections[section][@"title"];
    label.textAlignment = NSTextAlignmentLeft;
    [view addSubview:label];
    return view;
}


@end
